package com.chrishobson.race;

import com.chrishobson.awt.Capplet;

import java.awt.*;
import java.awt.event.*;


class Race1Thread extends Thread {


  public Race1Thread(Button mine, Button all) {
    m_me = mine;
    m_all = all;
  }


  public void run() {
    while(true) {
      m_me.setBackground(Color.green);
      for(int i = 1; i <= 250; ++i) {
        if(m_sync) {
          synchronized(s_obj) {
            incr(i);
          }
        } else {
          incr(i);
        }
        try {
          sleep(10);
          //sleep((int)(java.lang.Math.random()*100));
        } catch(Exception e) {}
        m_me.repaint();
      }
      m_me.setBackground(Color.red);
      suspend();
    }
  }


  private void incr(int my_count) {
    int val = s_val;
    ++val;
    m_me.setLabel(Integer.toString(my_count));
    s_val = val;
    m_all.setLabel(Integer.toString(s_val));
  }


  private Button m_me;
  private Button m_all;

  // data which is common to all race1thread instances

  public static int s_val;
  private static Object s_obj = new Object();
  private static boolean m_sync = false;
}


@SuppressWarnings("serial")
public class Race1 extends Capplet {

  public void init() {
    Race1Thread.s_val = 0;
    if(m_threads == null) {
      m_threads = new Race1Thread[4];
      Button l = new Button("000");
      for(int i = 0; i < 4; ++i) {
        Button b = new Button("000");
        add(b);
        m_threads[i] = new Race1Thread(b,l);
      }
      add(l);

      l = new Button("Restart");
      add(l);
      l.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          Race1Thread.s_val = 0;
          for(int i = 0; i < 4; ++i) {
            m_threads[i].resume();
          }
        }
      });
    }
  }

  public void start() {
    System.out.println("Start");
    if(m_started == false) {
      m_started = true;
      for(int i = 0; i < 4; ++i) {
        m_threads[i].start();
      }
    } else {
      for(int i = 0; i < 4; ++i) {
        m_threads[i].resume();
      }
    }
    System.out.println("Start Finished");
  }

  public void stop() {
    for(int i = 0; i < 4; ++i) {
      m_threads[i].suspend();
    }
  }

  public void destroy() {
    System.out.println("Destroy");
  }

  public void run() {
    System.out.println("Run");
  }

  Race1Thread m_threads[];
  boolean m_started = false;
}
